package offertest.test04;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

/**
 * @ClassName MiniThreadPool
 * @Description A minimal thread pool with core and max threads for interview
 * @Author ZJX
 * @Date 2025/4/12
 * @Version 1.0
 */
public class MiniThreadPool {
    private final BlockingQueue<Runnable> queue; // 任务队列
    private int activeThreads = 0; // 当前线程数
    private final int corePoolSize; // 核心线程数
    private final int maxPoolSize; // 最大线程数

    public MiniThreadPool(int corePoolSize, int maxPoolSize, int queueSize) {
        this.corePoolSize = corePoolSize;
        this.maxPoolSize = maxPoolSize;
        this.queue = new ArrayBlockingQueue<>(queueSize);

        // 初始化核心线程
        for (int i = 0; i < corePoolSize; i++) {
            addThread();
        }
    }

    // 创建工作线程
    private synchronized void addThread() {
        if (activeThreads >= maxPoolSize) {
            return;
        }
        Thread worker = new Thread(() -> {
            while (true) {
                try {
                    Runnable task = queue.take(); // 阻塞取任务
                    task.run(); // 执行任务
                } catch (InterruptedException e) {
                    break; // 中断时退出
                }
            }
        });
        activeThreads++;
        worker.start();
    }

    // 提交任务
    public void submit(Runnable task) throws InterruptedException {
        if (task == null) {
            throw new NullPointerException();
        }
        synchronized (this) {
            if (!queue.offer(task)) { // 队列满
                if (activeThreads < maxPoolSize) {
                    addThread(); // 创建新线程
                    queue.put(task); // 重新入队
                } else {
                    queue.put(task); // 阻塞等待
                }
            }
        }
    }
}